import {reqShopCartList,reqdeleteCart,reqCheckCart} from '@/api'
import {userTemp} from '@/utils/temp_token'
const state = {
    // 获取唯一的用户id
    userTempId: userTemp(),
    shopCartList:[]
}
const actions = {
   async getShopCart ({commit}){
       let result = await reqShopCartList();
    //    console.log(result.data);
       if(result.code == 200){
           commit('GETSHOPCART',result.data)
       }
   },
//    删除商品
   async deleteShop({commit},skuId){
       let result = await reqdeleteCart(skuId);
       if(result.code == 200){
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'))
       }
   },
//    改变选中的状态
    async changeCheck({commit},{skuId,isChecked}){
        let result = await reqCheckCart(skuId,isChecked);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 全选框
    async allCheck({dispatch,getters},isChecked){
        let arr= [];
        getters.shopList.cartInfoList.forEach(item=>{
            let promise = dispatch('changeCheck',{skuId:item.skuId,isChecked})
            arr.push(promise)
        }) 
        return Promise.all(arr)
    },
    // 删除选中的商品
    async deleteCheck({dispatch,getters}){
        let arr =[];
        getters.shopList.cartInfoList.forEach(item=>{
            if(item.isChecked == 1){
                let promise = dispatch('deleteShop',item.skuId)
                arr.push(promise)
            }
        })
        return Promise.all(arr);
    }
}
const mutations ={
    GETSHOPCART(state,shopCartList){
        // console.log(shopCartList)
        state.shopCartList = shopCartList
    }
}
const getters = {
    shopList(state){
           return state.shopCartList[0]|| {}
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}